package com.zhy.springcloud.contorller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.zhy.springcloud.enetities.CommonResult;
import com.zhy.springcloud.entities.Payment;
import com.zhy.springcloud.serivce.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author zhy
 * @Description
 * @ClassName CircleBreakController
 * @Date 2020/12/25 17:50
 **/
@RestController
@Slf4j
public class CircleBreakController {

    public static String SERVICE_URL="http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/concumer/fallback/{id}")
    //@SentinelResource(value = "fallback")//没有配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback")//fallbock只负责业务异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler")//blockHandler只负责setinel控制台配置违规
    //@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")//两个都配置 被限流降级的话就只能blockHandler处理
    @SentinelResource(value = "fallback",fallback = "handlerFallback",
            exceptionsToIgnore = {IllegalAccessException.class})//exceptionsToIgnore排除异常不走兜底方法
    public CommonResult fallback(@PathVariable Long id) throws IllegalAccessException {
        CommonResult forObject = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalAccessException("IllegalAccessException,非法参数");
        }else if (forObject.getData()==null){
            throw new NullPointerException("该id没有对应记录，空指针异常");
        }
        return forObject;
    }

    public CommonResult handlerFallback(@PathVariable Long id,Throwable e ){
        Payment payment = new Payment(id, null);
        return new CommonResult(444,"兜底异常"+e.getMessage(),payment);
    }

    public CommonResult blockHandler(@PathVariable Long id,Throwable e ){
        Payment payment = new Payment(id, null);
        return new CommonResult(445,"兜底异常"+e.getMessage(),payment);
    }

    @Resource
    private PaymentService paymentService;
    @GetMapping("/consumer/paymentSQL/{id}")
    public CommonResult paymentSQL(@PathVariable Long id){
        return paymentService.paymentSQL(id);
    }





}
